﻿using Core.Utility.Crypto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Helper
{
    /// <summary>
    /// 加解密工厂助手类
    /// </summary>
    public static class CryptoFactoryHelper
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="originalValue">原始值</param>
        /// <param name="saltValue">加盐值，拼接在首次原始值末尾</param>
        /// <param name="count">加密次数。最小值1</param>
        /// <param name="resultToUpperOrLower">结果转换为大写或小写，true转换为大写，false转换为小写，null不做任何转换</param>
        /// <returns>加密后的值</returns>
        public static string MD5(this string originalValue, string saltValue = "",uint count = 1,bool? resultToUpperOrLower = null)
        {
            string res = originalValue;
            if (!string.IsNullOrEmpty(originalValue))
            {
                //第一次加密的原始值
                res = CryptoFactory.CreateHashing(HashingProviderType.MD5).Signature($"{originalValue}{saltValue}", "");
                if (count > 1)
                {
                    for (int i = 1; i < count; i++)
                    {
                        res = CryptoFactory.CreateHashing(HashingProviderType.MD5).Signature(res, "");
                    }
                }
                if (resultToUpperOrLower == true)
                {
                    res = res.ToUpper();
                }
                else if (resultToUpperOrLower == false)
                {
                    res = res.ToLower();
                }
            }
            return res;
        }


        /// <summary>
        /// sha1加密
        /// </summary>
        /// <param name="originalValue">原始值</param>
        /// <param name="saltValue">加盐值，拼接在首次原始值末尾</param>
        /// <param name="count">加密次数。最小值1</param>
        /// <param name="resultToUpperOrLower">结果转换为大写或小写，true转换为大写，false转换为小写，null不做任何转换</param>
        /// <returns>加密后的值</returns>
        public static string SHA1(this string originalValue, string saltValue = "", uint count = 1, bool? resultToUpperOrLower = false)
        {
            string res = originalValue;
            if (!string.IsNullOrEmpty(originalValue))
            {
                //第一次加密的原始值
                res = CryptoFactory.CreateHashing(HashingProviderType.SHA1).Signature($"{originalValue}{saltValue}", "");
                if (count > 1)
                {
                    for (int i = 1; i < count; i++)
                    {
                        res = CryptoFactory.CreateHashing(HashingProviderType.SHA1).Signature(res, "");
                    }
                }
                if (resultToUpperOrLower == true)
                {
                    res = res.ToUpper();
                }
                else if (resultToUpperOrLower == false)
                {
                    res = res.ToLower();
                }
            }
            return res;
        }
    }
}
